package com.example.tabbar.utils

import android.os.Looper
import android.os.Handler
import com.example.tabbar.databinding.CustomNavBarBinding
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class StatusBarManager(private val customNavBarBinding: CustomNavBarBinding) {

    private val handler = Handler(Looper.getMainLooper())
    private val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())

    private val updateRunnable = object : Runnable {
        override fun run() {
            updateDateTime()
            // 计算下次更新的延迟时间，对齐下一分钟
            val delay = 60_000 - (System.currentTimeMillis() % 60_000)
            handler.postDelayed(this, delay)
        }
    }

    fun startUpdates() {
        // 立即显示当前时间
        updateDateTime()
        // 计算第一次延迟时间，对齐下一分钟
        val delay = 60_000 - (System.currentTimeMillis() % 60_000)
        handler.postDelayed(updateRunnable, delay)
    }

    fun stopUpdates() {
        handler.removeCallbacks(updateRunnable)
    }

    private fun updateDateTime() {
        val currentDateTime = timeFormat.format(Date())
        customNavBarBinding.date.text = currentDateTime
    }
    // 12时/24时制切换
    fun setTimeFormat(is24HourFormat: Boolean) {
        val pattern = if (is24HourFormat) "HH:mm" else "hh:mm"
        timeFormat.applyPattern(pattern)
        updateDateTime()
    }
}